package com.caration.shell.config;

import java.io.File;
import java.io.IOException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.caration.shell.R;

public class ExportAsyncTask extends AsyncTask<Object, Integer, String> {
	private ProgressDialog mProgressDialog;
	private Context mContext;

	protected final void onPostExecute(String result) {
		if (mProgressDialog.isShowing())
			mProgressDialog.dismiss();
		Toast.makeText(mContext, result, Toast.LENGTH_SHORT).show();
	}

	protected final void onPreExecute() {
		mProgressDialog.setMessage(mContext.getResources().getString(
				R.string.dbfile_export_dialog));
		mProgressDialog.show();
	}

	public ExportAsyncTask(Context context) {
		mContext = context;
		mProgressDialog = new ProgressDialog(context);
	}

	@Override
	protected String doInBackground(Object... params) {
		String result = "";
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File dataDBFile = new File(ConfigManger.DB_INTERNAL_PATH);
			File DBFile = new File(ConfigManger.DB_EXTENAL_PATH);
			File dataConfig = new File(ConfigManger.CONFIG_INTERNAL_PATH);
			File config = new File(ConfigManger.CONFIG_EXTENAL_PATH);
			try {
				if (DBFile.exists()) {
					DBFile.delete();
				}
				DBFile.createNewFile();
				ConfigManger.transferFile(dataDBFile, DBFile);

				if (config.exists()) {
					config.delete();
				}
				config.createNewFile();
				ConfigManger.transferFile(dataConfig, config);
				result = mContext.getResources().getString(
						R.string.dbfile_export_success);
			} catch (IOException e) {
				e.printStackTrace();
				result = mContext.getResources().getString(
						R.string.dbfile_export_error);
			}
		} else {
			result = mContext.getResources().getString(
					R.string.import_export_sdcard_unmounted);
		}

		return result;
	}
}
